package com.fingard.dsp.bank.directbank.cib03;

import com.fingard.common.utils.json.JSONUtils;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IQryRefund;
import com.fingard.dsp.bank.directbank.cib03.util.Base64;
import com.fingard.dsp.bank.directbank.cib03.util.Signature;
import com.fingard.dsp.bank.reqrespobj.qryrefund.ReqQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.RetAtsQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.detail.RetAtsRefundDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DEHelper;
import sun.misc.BASE64Decoder;

import java.util.Calendar;
import java.util.HashMap;

public class CIB03QryRefund extends CIB03Base implements IQryRefund {
    @Override
    public RetAtsQryRefund d_qry_refund(ReqQryRefund p_req) throws Exception {
        RetAtsQryRefund retAts = new RetAtsQryRefund(p_req.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.payAct, "");
            if (actItem == null) {
                tmpRespCode = "-1";
                tmpRespInfo = "未找到账号[" + p_req.payAct + "]商户配置信息";
                retAts.writeRespCode(tmpRespCode);
                retAts.writeRespInfo(tmpRespInfo);
                retAts.writeEnd();
                return retAts;
            }
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req.getQryStartDate());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req.getQryEndDate());
            tmpCalendarTo.add(Calendar.DAY_OF_MONTH, 1);

            while (tmpCalendarFrom.compareTo(tmpCalendarTo) == -1) {
                HashMap<String, String> postMapParams = new HashMap<String, String>();
                postMapParams.put("version", "1.0.2");
                postMapParams.put("mchtId", actItem.merchantId);
                postMapParams.put("signType", "RSA");
                postMapParams.put("serialNo", p_req.reqHeader.transSeqID);
                postMapParams.put("fileDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                postMapParams.put("mac", generateMAC(postMapParams, actItem));
                String tmpStrRet = sendDataToBank(JSONUtils.map2JSON(postMapParams), "qryRefund");
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    if (tmpStrRet.indexOf("{") >= 0) {
                        HashMap<String, String> tmpJsonRet = JSONUtils.json2Map(tmpStrRet);
                        if (tmpJsonRet.get("respCode").equals("E0000")) {
                            // 应答返回的加密对账文件内容
                            String encryptCheckFileContent = tmpJsonRet.get("fileContent");
                            WriteBankLogLn2("银行响应文件内容密文:\r\n" + encryptCheckFileContent);
                            byte[] decompressBytes = null;
                            // 应答返回的秘钥串
                            String aesKey = tmpJsonRet.get("aesKey");
                            if (StringHelper.hasAnyChar(aesKey)) {
                                // 用商户私钥证书对秘钥串进行解密
                                String key = Signature.decoderByCFCA(aesKey, actItem.ownKeyStorePath, actItem.ownKeyPassword);
                                WriteBankLogLn("解密后秘钥串aesKe:" + key);

                                // 用AES给文件内容解密
                                byte[] fileContent = Signature.AESDecode(encryptCheckFileContent, key);
                                // 用Base64给文件内容转码
                                byte[] b = Base64.decode(new String(fileContent, "UTF-8").toCharArray());
                                // 对文件内容进行解压缩
                                decompressBytes = DEHelper.uncompress(b);
                            } else {
                                decompressBytes = DEHelper.uncompress(new BASE64Decoder().decodeBuffer(encryptCheckFileContent));
                            }
                            String tmpFileContentRet = new String(decompressBytes, getCharset());
                            WriteBankLogLn2("银行响应退票内容:\r\n" + tmpFileContentRet);
                            String headLine = tmpFileContentRet.split("\n")[0];
                            if (!"0".equals(headLine.split("\\|")[2])) {
                                String fileDetailContent = tmpFileContentRet.substring(tmpFileContentRet.indexOf('\n') + 1);
                                fileDetailContent = fileDetailContent.substring(fileDetailContent.indexOf('\n') + 1);
                                String[] fileLine = fileDetailContent.split("\n");
                                for (String eachLine : fileLine) {
                                    if (eachLine == null || "".equals(eachLine)) {
                                        continue;
                                    }
                                    eachLine = eachLine + "1";
                                    String[] values = eachLine.split("\\|");
                                    if (values.length == 16) {
                                        RetAtsRefundDetail tmpRetDetail = new RetAtsRefundDetail();
                                        String[] temp = values[10].split("-");
                                        if (temp.length == 1) {
                                            tmpRetDetail.askNum = values[10];
                                        } else {
                                            tmpRetDetail.reqBatchNO = temp[0];
                                            tmpRetDetail.askNum = temp[1];
                                        }
                                        tmpRetDetail.recAct = values[7];
                                        tmpRetDetail.recActName = values[6];
                                        tmpRetDetail.amount = values[8];
                                        tmpRetDetail.refundTicketDate = Format.Date10Format.format(Format.Date8Format.parse(values[2]));
                                        tmpRetDetail.submitTime = Format.DateTimeFormat.format(Format.DateTime14Format.parse(values[2] + values[3]));
                                        tmpRetDetail.refundTicketReason = values[9];
                                        retAts.writeRetDetail(tmpRetDetail);
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "账单明细列数有误，实际为:" + values.length;
                                    }
                                }
                            }
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = "银行响应数据不合法";
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = "银行响应为空";
                    break;
                }
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsQryRefund(p_req.reqHeader);
            retAts.writeStart();
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("所查时间范围内无退票通知");
        }

        retAts.writeEnd();
        return retAts;
    }
}
